﻿#include <QDebug>
#include <QStandardPaths>
#include <QDir>
#include <QFile>

#include "FileDialogHelper.h"

QStringList FileDialogHelper::getFiles(const QString &directoryPath, const QStringList &nameFilters)
{
    QStringList files;

    QDir fileDir(directoryPath);

    QFileInfoList fileInfoList = fileDir.entryInfoList(nameFilters,  QDir::Files, QDir::Name);

    for (const QFileInfo& fileInfo: fileInfoList) {
        files << fileInfo.fileName();
    }

    return files;
}

QString FileDialogHelper::fullyQualifiedFilename(const QString &directoryPath, const QString &filename, const QStringList &nameFilters)
{
    QString firstFileExtention;

    // Check that the filename has one of the specified file extensions

    bool extensionFound = true;
    if (nameFilters.count()) {
        extensionFound = false;
        for (const QString& nameFilter: nameFilters) {
            if (nameFilter.startsWith("*.")) {
                QString fileExtension = nameFilter.right(nameFilter.length() - 2);
                if (fileExtension != "*") {
                    if (firstFileExtention.isEmpty()) {
                        firstFileExtention = fileExtension;
                    }
                    if (filename.endsWith(fileExtension)) {
                        extensionFound = true;
                        break;
                    }
                }
            } else if (nameFilter != "*") {
                qWarning() << "unsupported name filter format" << nameFilter;
            }
        }
    }

    // Add the extension if it is missing
    QString filenameWithExtension = filename;
    if (!extensionFound) {
        filenameWithExtension = QStringLiteral("%1.%2").arg(filename).arg(firstFileExtention);
    }

    return directoryPath + QStringLiteral("/") + filenameWithExtension;
}

bool FileDialogHelper::fileExists(const QString &filename)
{
    return QFile(filename).exists();
}

void FileDialogHelper::deleteFile(const QString &filename)
{
    QFile::remove(filename);
}
